package com.hopechart.micro.web.controller;

import com.github.pagehelper.PageInfo;
import com.hopechart.micro.common.constant.Response;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * <br/>
 * 基础控制层接口
 * </p>
 * 
 * @author daijiang@hopechart.com
 * @date 2017-10-30 09:46:57
 * @copyright 杭州鸿泉数字设备有限公司
 * @version V1.0.0
 */

public class BaseController {

	protected Response response(Integer code, String message, Object data) {
		return new Response(code, message, data);
	}

	protected Response response(Integer code, String message) {
		return new Response(code, message);
	}

	protected Map<String, Object> parseToRows(PageInfo pageInfo) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("rows", pageInfo.getList());
		map.put("total", pageInfo.getTotal());
		return map;
	}

	protected ModelAndView getModelAndView(String path) {
		return new ModelAndView(path);
	}

	protected ModelAndView redirect(String path) {
		return getModelAndView("redirect:" + path);
	}

	protected ModelAndView redirect(String path, String objName, Object obj) {
		return redirect(path).addObject(objName, obj);
	}

	protected ResponseEntity<InputStreamResource> downloadFile(String filePath) throws IOException {
		FileSystemResource file = new FileSystemResource(filePath);
		HttpHeaders headers = new HttpHeaders();
		headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
		headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getFilename()));
		headers.add("Pragma", "no-cache");
		headers.add("Expires", "0");

		return ResponseEntity.ok().headers(headers).contentLength(file.contentLength()).contentType(
				MediaType.parseMediaType("application/octet-stream")).body(
						new InputStreamResource(file.getInputStream()));
	}
}
